package com.wink.cachedemo.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wink.cachedemo.entity.User;
import com.wink.cachedemo.mapper.UserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xw
 * @date 2020/2/20 23:51
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> {

    private final UserMapper areaMapper;

    /**
     * 缓存是方法的返回值
     * cacheNames 缓存的名称
     * keyGenerator key生产策略
     * unless 缓存条件
     */
    @Cacheable(cacheNames = "expireKey", keyGenerator = "serviceKeyGenerator", unless = "#result == null")
    public List<User> getList() {
        return areaMapper.selectList(null);
    }

    public Boolean addUser(User user) {
        return areaMapper.insert(user) > 0;
    }

    /**
     * @CacheEvict:缓存清除
     * key:指定要清除的数据
     * allEntries = true : 指定清除这个缓存中的所有数据
     * beforeInvocation=fales: 缓存的清除是否在方法之前执行
     * 默认代表缓存清除操作是在方法执行之后执行；如果出现异常缓存就不会清除
     * beforeInvocation=true  代表清除缓存操作是在方法运行之前执行，无论方法是否出现异常，缓存都清除
     */
    @CacheEvict(cacheNames = "expireKey", allEntries = true, beforeInvocation = true)
    public Boolean deleteUser(Long id) {
        return areaMapper.deleteById(id) > 0;
    }

    /**
     * @CachePut: 既调用方法，又更新缓存数据；同步更新缓存
     * 修改了数据库的某个数据，同时更新缓存
     * 运行：
     * 1.先调用目标方法
     * 2.将目标方法的结果缓存起来
     */
    @CachePut(cacheNames = "expireKey")
    public Boolean updateUser(Long id, String password) {
        User user = areaMapper.selectById(id);
        user.setPassword(password);
        return areaMapper.updateById(user) > 0;
    }

    @Cacheable(cacheNames = "expireKey", keyGenerator = "serviceKeyGenerator", unless = "#result == null")
    public User getOne(Long id) {
        return areaMapper.selectById(id);
    }
}
